package 构造HTTP请求;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

//通过Java socket构造HTTP请求
//所谓的"发送HTTP请求",本质上就是安装HTTP的格式往TCP Socket中写入一个字符串.
//所谓的"接受HTTP请求",本质上就是从TCP Socket中读取一个字符串,再安装HTTP的格式来解析.
//我们基于Socket的知识,完全可以构造出一个简单的HTTP客户端程序,用来发送各种类型的HTTP请求
public class HttpClient {
    private Socket socket;
    private String ip;
    private int port;

    public HttpClient(String ip,int port) throws IOException {
        this.ip = ip;
        this.port = port;
        this.socket = new Socket(ip,port);
    }
    public String get(String url) throws IOException {
        //1.构造一个请求字符串
        StringBuffer request = new StringBuffer();
        //构造首行
        request.append("GET "+url+" HTTP/1.1\n");
        //构造首部header
        request.append("Host: "+this.ip+":"+this.port+"\n");
        //构造空行
        request.append("\n");
        //GET请求不需要body,就构造完成辣

        //2.发送数据,写入到socket里去
        OutputStream outputStream = socket.getOutputStream();
       //outputStream是一个字节流,以字节为单位进行写入,因此需要把StringBuilder转换成byte[]
        outputStream.write(request.toString().getBytes());

        //3.读取响应数据,从socket文件中读取
        InputStream response = socket.getInputStream();
        //搞一个1M大小的缓冲区,用来存放响应数据
        byte[] buffer = new byte[1024*1024];
        //n表示实际读到的字节数
        int n = response.read(buffer);
        return new String(buffer,0,n,"utf-8");
    }
    public String post(String url,String body) throws IOException {
        //1.构造字符串请求
        StringBuffer request = new StringBuffer();
        request.append("POST "+url+" HTTP/1.1\n");
        request.append("Host: "+this.ip+":"+this.port+"\n");
        request.append("Content-Type: text/plain\n");
        request.append("Content-Length:"+body.getBytes().length+"\n");
        request.append("\n");
        request.append(body);
        //2.发送请求,通过socket文件,交给服务器捏
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write(request.toString().getBytes());
        //3.接收响应,创建一个缓冲区,通过socket文件,来接受服务器返回给客户端的响应
        byte[] buffer = new byte[1024*1024];//1M
        InputStream inputStream = socket.getInputStream();
        int n = inputStream.read(buffer);//将响应读取到缓冲区里去捏
        return new String(buffer,0,n,"utf-8");
    }

    public static void main(String[] args) throws IOException {
        HttpClient httpClient = new HttpClient("42.192.83.143",8089);
//        String resp = httpClient.get("/AjaxMockServer/info");//这里是url是指具体路径
//        System.out.println(resp);
          String resp = httpClient.post("/AjaxMockServer/info","这是body");
        System.out.println(resp);
    }
}
